package com.btl.fragment.shequ;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.btl.bean.ZuiXin;
import com.btl.cygf.JiaoHuanActivity;
import com.btl.cygf.R;
import com.btl.cygf.TieZiActivity;
import com.btl.sqlite.DbOpService;
import com.btl.sqlite.History;
import com.btl.utils.DownTuUtils;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yzx.yunyanzhengdemo.activity.LoginActivity;

public class JiaohuanFragment extends Fragment implements OnClickListener{
	private Button jiaohuan;
	private PullToRefreshListView mListView;
	private LinkedList<ZuiXin> listItems1 = new LinkedList<ZuiXin>(); // 数据源集合
	//private ArrayAdapter<String> mAdapter;
	private MyListAdapter myListAdapter;
	private AsyncHttpClient client;
	private RequestParams params;
	private int v_id;
	private int lastid;
	Bitmap bitmap;

	@Override
	public void onClick(View v) {	
		
		SharedPreferences share =  getActivity().getSharedPreferences("login",
				Activity.MODE_PRIVATE);
		final String id = share.getString("id", "");
		if(!id.equals("")){
			Intent it = new Intent(getActivity(),LoginActivity.class);
			it.putExtra("type", "2");
			startActivity(it);
			
		} else {
			Intent intent = new Intent();
			intent.setClass(getActivity(), JiaoHuanActivity.class);
			startActivity(intent);
			
		}
		
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View messageLayout = inflater.inflate(R.layout.shequ_jiaohuan_layout,
				container, false);
		jiaohuan=(Button) messageLayout.findViewById(R.id.jiaohuanqu);
        jiaohuan.setOnClickListener(this);

		return messageLayout;
	}

	public JiaohuanFragment() {
	}


//
	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		/**
		 * 异步加载网络资源信息
		 */
		client = new AsyncHttpClient();
		// 像网络传输的数据
		params = new RequestParams();
		getDataRefresh();


		mListView = (PullToRefreshListView) getView().findViewById(
				R.id.list);

		mListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(getActivity(),
						System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
								| DateUtils.FORMAT_SHOW_DATE
								| DateUtils.FORMAT_ABBREV_ALL);

				// Update the LastUpdatedLabel
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

				// Do work to refresh the list here.
				if (mListView.isHeaderShown()) {
					// 下拉刷新
					getDataRefresh();
				} else if (mListView.isFooterShown()) {
					// 上拉加载
					getDataMore(v_id);

				}

			}

		});

		mListView.setMode(Mode.BOTH);
		mListView.getLoadingLayoutProxy(false, true).setPullLabel("加载完成");
		mListView.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载");
		mListView.getLoadingLayoutProxy(false, true).setReleaseLabel("上拉以加载");
		myListAdapter = new MyListAdapter();
		
		mListView.getRefreshableView().setAdapter(myListAdapter);

		// listItems = getListItems();
		//mListView.setAdapter(myListAdapter);

	}

	/**
	 * 连接到网络 获取数据
	 * 
	 * @param pagenow
	 */
	private void getDataRefresh() {
		// 实例LinkList数据源
		params.remove("sort");
		params.add("sort", "交换帖");
		listItems1 = new LinkedList<ZuiXin>();
		client.post(getResources().getString(R.string.url)+ "/CYGF/sendRefreshJason.post",params, new JsonHttpResponseHandler() {
			// 链接成功做出的反应
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONArray response) {
				for (int i = 0; i < response.length(); i++) {
					ZuiXin zuiXin = new ZuiXin();
					JSONObject object = response.optJSONObject(i);
					String s1 = object.optString("v_image");
					System.out.println(s1);
					String s2 = object.optString("v_title");
					String s3 = object.optString("v_address");
					String s4 = object.optString("p_id");
					int s5 = object.optInt("v_dianzan");
					String s6 = object.optString("p_nickname");
					int s7 = object.optInt("v_id");
					zuiXin.setPicture(s1);
					zuiXin.setTitle(s2);
					zuiXin.setAddress(s3);
					if (s6==null){
						zuiXin.setUsername(s4);
					}else {
						zuiXin.setUsername(s6);
					}
					zuiXin.setDianzan(s5);

					zuiXin.setVid(s7);
					lastid = object.optInt("lastid");
					listItems1.add(zuiXin);
					// listItems.addFirst(zuiXin);
					zuiXin = null;
					if (i==(response.length()-1)) {
						v_id = object.optInt("v_id");
					}
				}
				// BaseAdapter数据发生改变
				myListAdapter.notifyDataSetChanged();
				mListView.onRefreshComplete();
				super.onSuccess(statusCode, headers, response);
			}

			// 链接网络失败，做出的反应
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONArray errorResponse) {
				super.onFailure(statusCode, headers, throwable, errorResponse);
			}
		});
	}

	/**
	 * 下拉加载更多
	 */
	private void getDataMore(final int vid) {
		params.remove("v_id");
		params.add("v_id", vid + "");
		client.post(getResources().getString(R.string.url)
				+ "/CYGF/ClassificationMoreJSON", params,
				new JsonHttpResponseHandler() {
					// 链接成功做出的反应
					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONArray response) {
						Log.i("vid", vid + "");
						Log.i("vid", lastid + "");
						if (vid == lastid) {
							mListView.getLoadingLayoutProxy(false, true)
									.setRefreshingLabel("没有更多选项");
							// mListView.setMode(Mode.DISABLED);
							new GetDataTask().execute();
						} else {
							for (int i = 0; i < response.length(); i++) {
								ZuiXin zuiXin = new ZuiXin();
								JSONObject object = response.optJSONObject(i);
								String s1 = object.optString("v_image");
								System.out.println(s1);
								String s2 = object.optString("v_title");
								String s3 = object.optString("v_address");
								String s4 = object.optString("p_id");
								int s5 = object.optInt("v_dianzan");
								String s6 = object.optString("p_nickname");
								int s7 = object.optInt("v_id");
								zuiXin.setPicture(s1);
								zuiXin.setTitle(s2);
								zuiXin.setAddress(s3);
								if (s6==null){
									zuiXin.setUsername(s4);
								}else {
									zuiXin.setUsername(s6);
								}
								zuiXin.setDianzan(s5);

								zuiXin.setVid(s7);
								lastid = object.optInt("lastid");
								listItems1.add(zuiXin);
								// listItems.addFirst(zuiXin);
								zuiXin = null;
								if (i==(response.length()-1)) {
									v_id = object.optInt("v_id");
								}
							}
							// BaseAdapter数据发生改变
							myListAdapter.notifyDataSetChanged();
							mListView.onRefreshComplete();

						}
						super.onSuccess(statusCode, headers, response);
					}

					// 链接网络失败，做出的反应
					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONArray errorResponse) {
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
					}
				});
	}

	/**
	 * listview的适配器MyListAdapter
	 */
	private class MyListAdapter extends BaseAdapter {

		class ListItemView {
			public ImageView image;
			public TextView title;
			public TextView info;
			public TextView zuozhe;
			public TextView dianzanshu;
			public ImageView ditu;
		}

		@Override
		public int getCount() {
			return listItems1.size();
		}

		@Override
		public Object getItem(int position) {
			return listItems1.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			mListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					SharedPreferences share= getActivity().getSharedPreferences("login"  , Activity.MODE_WORLD_READABLE);
					String username = share.getString("id", "");
					if(!username.equals("")){
						SimpleDateFormat myFmt=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						Date now = new Date();
						History history = new History();
						history.setUsername(username);
						history.setVid(listItems1.get(position-1).getVid()+"");
						history.setTitle(listItems1.get(position-1).getTitle());
						history.setIntro(listItems1.get(position-1).getInfo());
						history.setVtime(myFmt.format(now));
						DbOpService db= new DbOpService(getActivity());
						db.Insert(history);
					}
					Intent intent = new Intent();
					intent.setClass(getActivity(), TieZiActivity.class);
					intent.putExtra("v_id",listItems1.get(position-1).getVid()+"");
					Log.i("v_id", listItems1.get(position-1).getVid()+"" );
					startActivity(intent);
				}
			});
			// final int selectID = position;
			// 自定义视图
			ListItemView listItemView = null;
			if (convertView == null) {
				listItemView = new ListItemView();
				// 获取list_item布局文件的视图
				convertView = LayoutInflater.from(getActivity()).inflate( R.layout.zuixin_item, null);
				// 获取控件对象
				
				listItemView.ditu = (ImageView) convertView
						.findViewById(R.id.ditubiaozhi);
				listItemView.image = (ImageView) convertView
						.findViewById(R.id.zuixin_view);
				listItemView.title = (TextView) convertView
						.findViewById(R.id.zuixin_name);
				listItemView.info = (TextView) convertView
						.findViewById(R.id.zuixin_info);
				listItemView.zuozhe = (TextView) convertView
						.findViewById(R.id.zuixin_zuozhe);
				listItemView.dianzanshu = (TextView) convertView
						.findViewById(R.id.dianzanshu);
				// 设置控件集到convertView
				
				listItemView.ditu.setVisibility(View.VISIBLE);
				convertView.setTag(listItemView);
			} else {
				listItemView = (ListItemView) convertView.getTag();
			}

			final String str = JiaohuanFragment.this.listItems1.get(position)
					.getPicture();
			System.out.println(str);
			System.out.println(JiaohuanFragment.this.listItems1.get(position)
					.getTitle());

			ImageLoader imageLoader = ImageLoader.getInstance();

			imageLoader.init(DownTuUtils.getConfig(getActivity()));

			imageLoader.displayImage(str, listItemView.image,
					DownTuUtils.getOptions());

			// listItemView.image.setImageBitmap(new
			// BitmapFactory().decodeByteArray(data, offset, length))
			listItemView.title.setText(JiaohuanFragment.this.listItems1.get(position).getTitle());
			listItemView.info.setText(JiaohuanFragment.this.listItems1.get(position).getAddress());
			listItemView.zuozhe.setText(JiaohuanFragment.this.listItems1.get(position).getUsername());
			listItemView.dianzanshu.setText(JiaohuanFragment.this.listItems1.get(position).getDianzan()+ "");
			return convertView;
		}

	}

	private class GetDataTask extends AsyncTask<Void, Void, String> {

		// 后台处理部分
		@Override
		protected String doInBackground(Void... params) {
			// Simulates a background job.
			// mListView.getLoadingLayoutProxy(false,
			// true).setRefreshingLabel("没有更多选项");
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
			}
			String str = "Added after refresh...I add";
			return str;
		}

		// 这里是对刷新的响应，可以利用addFirst（）和addLast()函数将新加的内容加到LISTView中
		// 根据AsyncTask的原理，onPostExecute里的result的值就是doInBackground()的返回值
		@Override
		protected void onPostExecute(String result) {

			// 通知程序数据集已经改变，如果不做通知，那么将不会刷新mListItems的集合
			// myListAdapter.notifyDataSetChanged();
			// 32tCall onRefreshComplete when the list has been refreshed.
			mListView.onRefreshComplete();
			super.onPostExecute(result);
		}
	}


}
